
//vuex配置在这里

import getUserTempId from "@/utils/userTempId";
import { reqLogin, reqLogout, reqUserInfo } from "@/api";

const state = {
  userTempId: getUserTempId(),
  token: localStorage.getItem("token") || "",
  userInfo: {
    nickName:"",
  },
};
//唯一可以修改state数据的方法
const mutations = {
  //大写为，常量
  SET_TOKEN_STATE(state, payload) {
    //使用传参
    state.token = payload.token;
  },
  SET_USERINFO_STATE(state, payload) {
    state.userInfo = payload.userInfo;
  },
  RESET_USERINFO_STATE(state){
    state.token ="";
    state.userInfo = {nickName:""};
    localStorage.removeItem("token");
  }
};
const actions = {
  //处理异步
  async getToken({ commit }, userInfo) {
    try {
      const result = await reqLogin(userInfo)
      localStorage.setItem("token", result.token);
      commit("SET_TOKEN_STATE", { token: result.token })
    } catch (e) {
      return Promise.reject(e);
    }
  },
  //
  async getUserInfo({ commit }) {
    try {
      const result = await reqUserInfo();
      commit("SET_USERINFO_STATE", { userInfo: result })
    } catch (e) {
      return Promise.reject(e.message)
    }
  },
  getResetUser({commit}){
    commit("RESET_USERINFO_STATE");
  },
  async getLogout({ commit }) {
    try {
      await reqLogout();
      //退出登录成功以后,还是要清空所有的用户信息
      commit("RESET_USERINFO_STATE");
    } catch (e) {
      return Promise.reject(e);
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
